/**
 * 
 */
package hu.cubussapiens.cms;

import hu.cubussapiens.facts.BlobData;
import hu.cubussapiens.facts.StringData;
import hu.cubussapiens.facts.query.IQueryContext;
import hu.cubussapiens.facts.query.QueryContext;

import java.io.IOException;
import java.io.InputStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.datastore.Blob;

/**
 * @author balazs.grill
 *
 */
public class DataServlet extends HttpServlet {

	private static final int DATABUFFER = 4096;
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 7737212207666125467L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		IQueryContext context = new QueryContext(null);
		
		String literal = req.getParameter("literal");
		StringData data = context.getLiteral(literal);
		
		if (data == null) {
			resp.sendError(404);
			return;
		}
		if (context.canAccess(data.getRead())){
			BlobData bdata = context.getBlobData(data.getId());			
			if (bdata == null){
				resp.sendError(404);
				return;
			}
			resp.setContentType(bdata.getContentType());
			resp.getOutputStream().write(bdata.getData().getBytes());
			resp.setStatus(200);
		}else{
			resp.sendError(403);
			return;
		}
	}
	
	private byte[] read(InputStream is) throws IOException{
		byte[] data = new byte[0];
		byte[] buff = new byte[DATABUFFER];
		int result = -1;
		while((result = is.read(buff)) != -1){
			byte[] newdata = new byte[data.length+result];
			System.arraycopy(data, 0, newdata, 0, data.length);
			System.arraycopy(buff, 0, newdata, data.length, result);
			data = newdata;
		}
		return data;
	}
	
	@Override
	protected void doPut(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		IQueryContext context = new QueryContext(null);
		
		String literal = req.getParameter("literal");
		String contentType = req.getParameter("contenttype");
		StringData data = context.getLiteral(literal);
		
		if (data == null) {
			resp.sendError(404);
			return;
		}
		if (context.canAccess(data.getRead())){
			BlobData bdata = context.getBlobData(data.getId());
			InputStream is = req.getInputStream();
			Blob blob = new Blob(read(is));
			if (bdata == null){
				bdata = new BlobData();
				bdata.setRef(data.getId());
			}
			bdata.setData(blob);
			bdata.setContentType(contentType);
			context.getManager().makePersistent(bdata);
			resp.setStatus(200);
		}else{
			resp.sendError(403);
			return;
		}
	}
	
}
